package com.shigu.shareImg.service;

import com.google.zxing.WriterException;
import com.opentae.data.mall.beans.MallItem;
import com.opentae.data.mall.beans.ManagerMallUser;
import com.opentae.data.mall.beans.UserInviteInfo;
import com.opentae.data.mall.interfaces.MallItemMapper;
import com.opentae.data.mall.interfaces.ManagerMallUserMapper;
import com.opentae.data.mall.interfaces.UserInviteInfoMapper;
import com.shigu.HostUtil;
import com.shigu.constant.enums.PageUri;
import com.shigu.constant.enums.SystemConstant;
import com.shigu.constant.service.SystemConstantService;
import com.shigu.exceptions.WapException;
import com.shigu.shareImg.util.NewImageUtils;
import com.shigu.shareImg.vo.InviteImageResponse;
import com.shigu.shareImg.vo.JointPicResponse;
import com.shigu.user.OSS.OssIO;
import com.shigu.user.service.MallTokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;


/*
 * create by  过儿  2019-05-14
 *
 */
@Service
public class SnsImgService {
    @Autowired
    MallItemMapper mallItemMapper;
    @Value("${web_host}")
    private String webHost;
    @Value("${shareUri}")
    private String shareUri;
    private final int rowWidth = 13;//一行的字数

    @Autowired
    MallTokenService mallTokenService;
    @Autowired
    ManagerMallUserMapper managerMallUserMapper;
    @Autowired
    UserInviteInfoMapper userInviteInfoMapper;

    @Autowired
    SystemConstantService systemConstantService;
    @Autowired
    NewImageUtils newImageUtils;
    @Autowired
    OssIO ossIo;

    /**
     * @description
     * @author 郭尔
     * @date 2019-05-17 10:24
     */
    public JointPicResponse getJointPic(String itemId, String token) throws WriterException {
        String url = writeToOss(Long.valueOf(itemId), token);
        return new JointPicResponse(url).success();
    }


    /**
     * @description
     * @author 郭尔
     * @date 2019-05-14 17:11
     */
    @Cacheable(value = "sns_image_catch", key = "#itemId + '_' + #token")
    public String writeToOss(Long itemId, String token) throws WriterException {
        Long id = mallTokenService.selUserIdByToken(token);
        ManagerMallUser user = managerMallUserMapper.selectByPrimaryKey(id);
        MallItem item = mallItemMapper.selectByPrimaryKey(itemId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String url = "";
        String[] img = item.getImages().split(",");
        String filePath = "app/mall/sns/" + sdf.format(new Date()) + "/" + token + "/" + item.getItemId() + "_" + System.currentTimeMillis() + ".jpg";
        String shareUrl = webHost + shareUri + "?itemId=" + itemId + "&sharer=" + token;
        BufferedImage image = shareImg(img[0], item.getTitle(), item.getDiscount().toString(), item.getPrice().toString(), shareUrl,user.getNick());

        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", os);
            InputStream is = new ByteArrayInputStream(os.toByteArray());
            url = ossIo.uploadFile(is, filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return url;
    }

    /**
     * @param discount 价格
     * @param price    原价
     * @param picUrl   主图链接
     * @description
     * @author 郭尔
     * @date 2019-11-06 9:40
     */
    public BufferedImage shareImg(String picUrl, String title, String discount, String price, String shareUrl,String username) throws WriterException {
        //首图
        BufferedImage picImage = newImageUtils.modifySize(newImageUtils.loadImageUrl(picUrl), 650, 650);
        //画下面的图
        //左边文字区，右边二维码
        BufferedImage qrCode = newImageUtils.qrCode(shareUrl, 200, 200);

        //左边依次调整字号和文字
        //左边纯白的背景
        BufferedImage textImage = newImageUtils.drawPureColor(450, 200, Color.WHITE);
        //写商品名称
        newImageUtils.setFont("SimHei", 36);
        BufferedImage btmLeft = newImageUtils.modifyImage(textImage, changeRow(title, 2), 0, 61, false);
        //价格
        discount = "￥" + discount;
        newImageUtils.setFont("SimHei", 48);
        BufferedImage disImage = newImageUtils.modifyImage(btmLeft, discount, 0, 162, new Color(255, 20, 79));
        //原价
        price = "原价:￥" + price;
        newImageUtils.setFont("SimHei", 28);
        BufferedImage priceImage = newImageUtils.modifyImage(disImage, price, 228, 162, new Color(153, 153, 153));
        //左右拼接起来
        BufferedImage bottom = newImageUtils.sideImg(priceImage, qrCode);
        //再把上下拼接起来
        BufferedImage middleImage = newImageUtils.spliceImg(picImage, bottom);
        //获取背景
        String background = "http://cailifu.oss-cn-hangzhou.aliyuncs.com/app/mall/2019/11/06/1573010356203.png";
        BufferedImage ground = newImageUtils.modifySize(newImageUtils.loadImageUrl(background),750,1095);
        //把图片放到背景图的中间
        BufferedImage base = newImageUtils.modifyImages(middleImage, ground, 200);
        //对这张图片操作
        newImageUtils.setFont("SimHei",20);

        BufferedImage scanCode = newImageUtils.modifyImage(base, "扫码查看详情", 535, 1050, new Color(153, 153, 153));
        BufferedImage shareFrom = newImageUtils.modifyImage(scanCode, "来自 "+username+" 的分享", 50, 180, new Color(153, 153, 153));
        return shareFrom;
    }


    private Object[] changeRow(String content, int maxRow) {
        List<String> a = new ArrayList<>();
        int flag = (content.length() % rowWidth) > 0 ? 1 : 0;
        int n = content.length() / rowWidth + flag;
        int size = n < maxRow ? n : maxRow;
        for (int i = 0; i < size; i++) {
            int start = i * rowWidth;
            int end = (i + 1) * rowWidth - 1;
            if (end > content.length()) {
                a.add(content.substring(start));
            } else {
                a.add(content.substring(start, end));
            }
        }
        return a.toArray();
    }


    /**
     *
     * @description
     * @author 郭尔
     * @date 2019-11-19 12:39
     */
    public BufferedImage registerImage(String baseUrl) throws WriterException {
        //oss上的背景图片
        String backGround = "http://cailifu.oss-cn-hangzhou.aliyuncs.com/app/mall/sns/1574141931769_qrRegist.png";
        BufferedImage bg = newImageUtils.loadImageUrl(backGround);
        //把邀请链接生成二维码
        BufferedImage qrCode = newImageUtils.qrCode(baseUrl, 350, 350);
        //二维码 放到背景图片中
       return newImageUtils.modifyImages(qrCode,bg,196,1124);
    }

    /**
     *
     * @description
     * @author 郭尔
     * @date 2019-11-19 15:27
     */
    public InviteImageResponse getInviteImgSrc(Long mallUserId) throws WapException {
        InviteImageResponse response = new InviteImageResponse();
        UserInviteInfo info = userInviteInfoMapper.selectByPrimaryKey(mallUserId);
        String qrCodeUrl = "https://" + HostUtil.selHost() + "/invite/register?code=" + info.getInviteCode();
//        String qrCodeUrl = "http://" + HostUtil.selHost() + "/invite/register?code=" + info.getInviteCode();
        String inviteImgSrc;
        //判断是否存在图片
        if (StringUtils.isBlank(info.getRegisteImgUrl())) {
            //不存在，则去生成图片
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            //上传图片
            try {
                BufferedImage bufferedImage = registerImage(qrCodeUrl);

                String filePath = "app/mall/sns/qrRegist/" + sdf.format(new Date()) + "/" + System.currentTimeMillis() + ".jpg";
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                ImageIO.write(bufferedImage, "jpg", os);
                InputStream is = new ByteArrayInputStream(os.toByteArray());
                inviteImgSrc = ossIo.uploadFile(is, filePath);

                info.setRegisteImgUrl(inviteImgSrc);
                userInviteInfoMapper.updateByPrimaryKeySelective(info);
            } catch (Exception e) {
                e.printStackTrace();
                throw new WapException("获取图片失败");
            }
        }else {
            inviteImgSrc = info.getRegisteImgUrl();
        }
        //获取系统设置的文本
        Map<String, String> map = systemConstantService.selPageConstant(PageUri.system.toString());
        String snsText = map.get(SystemConstant.registSnsText.toString());
        Integer type =Integer.valueOf( map.get(SystemConstant.wxSnsType.toString()) );
        String text = snsText +"\n"+qrCodeUrl;

        response.setInviteImgSrc(inviteImgSrc);
        response.setInviteText(text);
        response.setSendWxConType(type);
        return response.success();
    }
}
